import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { FormItemProps } from "@/views/learn/courses/utils/types";
import editForm from "@/views/learn/courses/form.vue";
import dayjs from "dayjs";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import {
  coursesAdd,
  coursesDel,
  coursesUpdate,
  getCoursesList
} from "@/api/learn/courses";
import { addDialog } from "@/components/ReDialog/index";
import { deviceDetection } from "@pureadmin/utils";

export function useCourses() {
  const form = reactive({
    name: "",
    pageSize: 10,
    currentPage: 1
  });
  const loading = ref(true);
  const isShow = ref(false);
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  // 表格列
  const columns: TableColumnList = [
    {
      label: "编号",
      prop: "id"
    },
    {
      label: "宣传图",
      prop: "attachmentList",
      width: 120,
      // 单元格处理 tsx

      cellRenderer: ({ row }) => {
        if (row.attachmentList.length === 0) {
          return <div>暂无宣传图</div>;
        }
        const iamges = row.attachmentList.map(item => {
          return import.meta.env.VITE_STATIC_URL + item.filePath;
        });
        return (
          <el-image
            fit="cover"
            preview-teleported={true}
            src={iamges.length > 0 ? iamges[0] : ""}
            preview-src-list={[...iamges]}
            class="w-[24px] h-[24px] rounded-full align-middle"
          />
        );
      }
    },
    {
      label: "名称",
      prop: "name"
    },
    {
      label: "创建时间",
      prop: "createdAt",
      minWidth: 160,
      formatter: ({ createdAt }) =>
        dayjs(createdAt).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  // 分页
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 查询列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getCoursesList(toRaw(form));
    dataList.value = [...data.lists];
    pagination.total = data.pagination.total;
    pagination.pageSize = data.pagination.pageSize;
    pagination.currentPage = data.pagination.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  async function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    await onSearch();
  }

  // 新增 修改
  async function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}课程`,
      props: {
        formInline: {
          categoryId: row?.categoryId || "",
          id: row?.id || 0,
          userId: row?.userId || 0,
          name: row?.name || "",
          image: row?.image || "",
          recommended: row?.recommended || true,
          introductory: row?.introductory || true,
          content: row?.content || "",
          categoryList: row?.categoryList || [],
          fileList: row?.fileList || []
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const { data } = await coursesAdd(curData);
              formRef.value.getUploadRef().upload({
                businessId: data.id,
                tableName: "courses",
                filePath: ""
              });
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              formRef.value.getUploadRef().upload();
              await coursesUpdate(Object.assign({ id: row.id }, curData));
              chores();
            }
          }
        });
      }
    });
  }

  // 删除
  async function handleDelete(row) {
    await coursesDel({ id: row.id });
    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
    await onSearch();
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  // handle pageSize
  async function handleSizeChange(val: number) {
    form.pageSize = val;
    await onSearch();
  }

  // handle currentPage
  async function handleCurrentChange(val: number) {
    form.currentPage = val;
    await onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  onMounted(async () => {
    await onSearch();
  });

  return {
    form,
    isShow,
    columns,
    loading,
    openDialog,
    onSearch,
    rowStyle,
    dataList,
    pagination,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    handleDelete,
    resetForm
  };
}
